#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 10

int main(int argc, char *argv[])
{
  int pfd[2];
  char buf[BUF_SIZE];
  ssize_t numRead;

  if (argc != 2 || strcmp(argv[1], "--help") == 0)
    printf("Usage error!\n");
  if(pipe(pfd) == -1)
    printf("Failed to create a pipe\n");

  switch (fork()) {
  case -1:
    printf("Failed to fork a process\n");
    exit(-1);
  case 0: //child process
    sleep(3);
    if (close(pfd[1] == -1) )
      printf("Failed to close the write end of the pipe\n");
    numRead = read(pfd[0], buf, BUF_SIZE);
    if (numRead == -1)
      printf("Failed to read from pipe\n");
    if (numRead == 0)
      break; //End of file
    if (write(STDOUT_FILENO, buf, numRead) != numRead)
      printf("Failed to write to STDOUT\n");
    write(STDOUT_FILENO, "\n" ,1);
    if (close(pfd[0]) == -1)
      printf("Failed to close read pipe\n");
    _exit(EXIT_SUCCESS);

  default: //parent process
    if (close(pfd[0] == -1) )
      printf("Failed to close read pipe\n");
    if (write(pfd[1], argv[1], strlen(argv[1])) != strlen(argv[1]) )
      printf("Failed to write to pipe\n");
    if (close(pfd[1]) == -1)
      printf("Failed to close write pipe\n");
    wait(NULL);
    exit(EXIT_SUCCESS);
      
  }
}
